package xhwl.android.pay.invoke;

import android.app.Activity;
import android.widget.Toast;

import de.greenrobot.event.EventBus;
import xhwl.android.pay.bean.PayBean;
import xhwl.android.pay.bean.WXPayBean;
import xhwl.android.pay.common.AlipayMgr;
import xhwl.android.pay.common.Constants;
import xhwl.android.pay.common.WxpayMgr;

import static xhwl.android.pay.bean.PayBean.PayType.TYPE_WX;
import static xhwl.android.pay.bean.PayBean.PayType.TYPE_ZFB;

public class PayManager {

	private static volatile PayManager instance;
	private PayManager(){}
	public static PayManager getInstance(){
		if(instance==null)
			synchronized (PayManager.class) {
				if(instance==null)
				{
					instance=new PayManager();
				}
			}
		return instance;
	}
	public static void initWX(boolean enable,String appId,String apiKey,String mchId){
		Constants.WEIXIN_PAY_ENABLE=enable;
		Constants.APP_ID=appId;
		Constants.API_KEY=apiKey;
		Constants.MCH_ID=mchId;
	}
	/**
	 * @param ctx
	 * @param payBean
	 */
	public void startPayment(final Activity ctx, final PayBean payBean)
	{	
		String msg="";
		if(ctx==null||payBean==null){
			return;
		}
		if(payBean.getOrderNo()==null||payBean.getOrderNo().length()==0){
			msg="订单号不能为空！";
		}
		else if(payBean.getOrderName()==null||payBean.getOrderName().length()==0){
			msg="订单名称不能为空！";
		}
		else if(payBean.getMoney()==null||payBean.getMoney().length()==0){
			msg="订单金额不能为空！";
		}
		else if(payBean.getPayType()!= TYPE_ZFB&&payBean.getPayType()!= TYPE_WX){
			msg="请选择一种支付方式！";
		}
		else{
			try {
				double m=Double.parseDouble(payBean.getMoney());
				if(m<=0){
					msg="订单金额小于或等于0！";
				}
			} catch (Exception e) {
				// TODO: handle exception
				msg="订单金额格式错误！";
			}
		}
		if(msg.length()>0)
		{
			Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
			return;
		}
        if(payBean.getPayType()==TYPE_WX) {
        	if(Constants.WEIXIN_PAY_ENABLE){
        		if(payBean instanceof WXPayBean)
				{
					WXPayBean payBean1= (WXPayBean) payBean;
					new WxpayMgr(ctx, payBean1).pay();
				}

        	}
        	else
        	{
        		Toast.makeText(ctx,"暂未开通微信支付",Toast.LENGTH_LONG).show();
        	}
        }
        else if(payBean.getPayType()==TYPE_ZFB)
        {
            AlipayMgr mgr=new AlipayMgr(ctx,payBean,new PaymentCallback() {
				
				@Override
				public void onResult(boolean success,String serialNumOrErrMsg) {
					// TODO Auto-generated method stub
					if(success){
						EventBus.getDefault().post(new PaymentResult(payBean.getOrderNo(),success, serialNumOrErrMsg));
					}
					else
					{
						Toast.makeText(ctx,serialNumOrErrMsg,Toast.LENGTH_SHORT).show();
					}
				}
			});
            mgr.pay();
        }
	}

}
